package com.stackroute.favouriteservice.service;

import com.stackroute.favouriteservice.domian.Favourite;
import com.stackroute.favouriteservice.repository.FavouriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: cimatch
 * @author: Brian Huang
 * @create: 2019-06-30 17
 **/
@Service
public class FavouriteService {

    @Autowired
    private FavouriteRepository favouriteRepository;

    @Autowired
    private FavouriteMqService favouriteMqService;

    public Favourite save(Favourite favourite) throws Exception {

        if(getByUniqueId(favourite)){
            throw new Exception("Favourite already exit");
        }
        Favourite favourite2 = favouriteRepository.save(favourite);

        if(favourite2 != null){
            favouriteMqService.addFavourite(favourite);
        }
       // favouriteMqService.addFavourite(favourite);
        return favourite;

    }

    private boolean getByUniqueId(Favourite favourite){
        Favourite favourite1 =
                favouriteRepository.findByUniqueIdAndUserId(favourite.getUniqueId(), favourite.getUserId());
        if(favourite1 != null) {
            return true;
        }
        return false;
    }

    public List<Favourite> getFavourites(String userId){
         return   favouriteRepository.findByUserId(userId);
    }


}
